package cn.karent.domain;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

/**
 * @author wanshengdao
 * @date 2025/4/19
 */
@Slf4j
@Service
@RefreshScope
@RequiredArgsConstructor
public class FileService {

    @Value("${upload-path}")
    private String uploadPath;

    @Value("${access-prefix}")
    private String accessPrefix;

    private void checkPath() {
        Assert.isTrue(StringUtils.isNotBlank(uploadPath), "上传路径不能为空");
        Assert.isTrue(StringUtils.isNotBlank(accessPrefix), "上传路径不能为空");
    }

    public String upload(String dir, MultipartFile file) {
        checkPath();
        String path = uploadPath + "/" + dir;
        File uploadDir = new File(path);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        log.info("上传的路径: {}", uploadDir.getAbsolutePath());
        File localFile = new File(uploadDir, file.getOriginalFilename());
        try {
            file.transferTo(localFile);
        } catch (IOException e) {
            throw new IllegalStateException("上传文件失败", e);
        }
        String accessPath = String.format("%s/%s/%s", accessPrefix, dir, file.getOriginalFilename());
        log.info("上传的文件: {}, 访问前缀: {}", localFile.getAbsolutePath(), accessPath);
        return accessPath;
    }

}
